package com.example.jetpack04.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.example.jetpack04.R;
import com.example.jetpack04.databinding.RecycleItemBinding;
import com.example.jetpack04.model.User;

import java.util.List;

public class MyRecycleViewAdapter extends RecyclerView.Adapter<MyRecycleViewAdapter.MyViewHolder> {

    private List<User> users ;

    class MyViewHolder extends RecyclerView.ViewHolder{

        private RecycleItemBinding recycleItemBinding ;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
        }

        public MyViewHolder(RecycleItemBinding recycleItemBinding) {
            super(recycleItemBinding.getRoot());
            this.recycleItemBinding = recycleItemBinding;
        }
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    //创建viewholder ，给viewholder绑定视图
    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        RecycleItemBinding recycleItemBinding = DataBindingUtil.inflate(
                LayoutInflater.from(parent.getContext()) ,
                R.layout.recycle_item,
                parent,false);
        MyViewHolder myViewHolder = new MyViewHolder(recycleItemBinding);
        return myViewHolder;
    }

    //给viewholder绑定的视图设置数据
    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.recycleItemBinding.setUser(users.get(position));
    }

    @Override
    public int getItemCount() {
        return users.size();
    }

    public void toTop(int positionIndex){
        //先删除
        User user = users.get(positionIndex);
        users.remove(positionIndex);
        notifyItemRemoved(positionIndex);
        //移动到顶部 一定要把数据放在开头
        users.add(0,user);
        notifyItemInserted(0);
    }


    public void delete(int positionIndex){
        users.remove(positionIndex);
         notifyItemRemoved(positionIndex);
    }

    public void loadMore(List<User> us){
        //插入的起始位置
        int start = getItemCount();
        int end = start+us.size();
        users.addAll(us);
        notifyItemRangeInserted(start,end);
    }

}
